package com.my.service.impl;

import com.my.service.BusinessService;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.my.service.StockService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Service
public class StockServiceImpl implements StockService {
    @Resource
    private LoadBalancerClient loadBalancerClient;//ribbon负载均衡器

    private String getUrl(String str) {
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("stock-provider");
        return "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/stock/" + str;
    }

    @Override
    public String in(Integer goods_id, Integer orders_id, Integer type, Integer num) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("goods_id", goods_id);
        map.add("orders_id", orders_id);
        map.add("type", type);
        map.add("num", num);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(getUrl("in"), request, String.class);
        return response.getBody();
    }

    @Override
    public String showAll(String context, Integer currentPage, Integer pageSize, String sort, Boolean asc, HttpServletRequest req) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add("token", req.getHeader("token"));
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("context", context);
        map.add("currentPage", currentPage);
        map.add("pageSize", pageSize);
        map.add("sort", sort);
        map.add("asc", asc);
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(getUrl("showAll"), request, String.class);
        return response.getBody();
    }
}
